package com.jielihaofeng.springboot.shorturl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jielihaofeng.springboot.shorturl.constant.UrlConstants;
import com.jielihaofeng.springboot.shorturl.entity.ShortUrl;
import com.jielihaofeng.springboot.shorturl.mapper.ShortUrlMapper;
import com.jielihaofeng.springboot.shorturl.service.ShortUrlService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jielihaofeng.springboot.shorturl.util.ShortUrlUtil;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Johnnie Wind
 * @since 2021-06-03
 */
@Service
public class ShortUrlServiceImpl extends ServiceImpl<ShortUrlMapper, ShortUrl> implements ShortUrlService {

    @Override
    public String getShortUrl(String url) {

        // 查询数据库是否存在
        QueryWrapper<ShortUrl> shortUrlQueryWrapper = new QueryWrapper<>();
        shortUrlQueryWrapper.eq("url", url);
        ShortUrl shortUrlDb = getOne(shortUrlQueryWrapper);
        if (shortUrlDb != null) {
            return UrlConstants.shortSystemUrl.concat(shortUrlDb.getShortKey());
        }

        // 不存在则生成
        String shortKey = ShortUrlUtil.nextOne();

        // 保存入库
        ShortUrl shortUrl = new ShortUrl();
        shortUrl.setShortKey(shortKey);
        shortUrl.setUrl(url);
        save(shortUrl);

        return UrlConstants.shortSystemUrl.concat(shortKey);
    }

    @Override
    public String updateShortUrl(String url) {

        // 查询数据库是否存在
        QueryWrapper<ShortUrl> shortUrlQueryWrapper = new QueryWrapper<>();
        shortUrlQueryWrapper.eq("url", url);
        ShortUrl shortUrlDb = getOne(shortUrlQueryWrapper);

        // 如果原来没有，则不生成，返回
        if (shortUrlDb == null) {
            return null;
        }

        // 生成新的短链
        String shortKey = ShortUrlUtil.nextOne();

        // 更新
        shortUrlDb.setShortKey(shortKey);
        updateById(shortUrlDb);

        return UrlConstants.shortSystemUrl.concat(shortKey);
    }

    @Override
    public String getUrl(String shortKey) {
        // 查询数据库是否存在
        QueryWrapper<ShortUrl> shortUrlQueryWrapper = new QueryWrapper<>();
        shortUrlQueryWrapper.eq("short_key", shortKey);
        ShortUrl shortUrlDb = getOne(shortUrlQueryWrapper);
        if (shortUrlDb==null){
            return null;
        }
        return shortUrlDb.getUrl();
    }

}
